package com.shardings.selfdefined;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;


import java.util.*;

/**
 * @author: LCG
 * @date: 2022-11-13 14:43:22
 * @description: 自定义 多字段分片算法 按照数据表划分 这个是复合分片的算法的自定义分片算法
 *               这里的这个泛型是指的是 分片字段的类型
 **/
@Slf4j
public class MyComplexShardingAlgorithmTB implements ComplexKeysShardingAlgorithm {

    private static final String col1="id";
    private static final String col2="userName";

    @Override
    public Collection<String> doSharding(Collection collection, ComplexKeysShardingValue complexKeysShardingValue) {

        String logicTableName = complexKeysShardingValue.getLogicTableName();

        Map columnNameAndShardingValuesMap = complexKeysShardingValue.getColumnNameAndShardingValuesMap();
        //between  and 的值
        Map columnNameAndRangeValuesMap = complexKeysShardingValue.getColumnNameAndRangeValuesMap();
        List c1Id = (List) columnNameAndShardingValuesMap.get(col1);

        List c2UserName = (List) columnNameAndShardingValuesMap.get(col2);

        if(Optional.ofNullable(c1Id).isPresent()||Optional.ofNullable(c2UserName).isPresent()){

            StringBuffer sb=new StringBuffer(c1Id.get(0).toString());

            sb.append(c2UserName.get(0));

            int i = (sb.toString().hashCode()& Integer.MAX_VALUE) % collection.size();
            log.info("======余数==={}======id={}=userName={}",i,c1Id,c2UserName);
            Object[] stt=new Object[collection.size()];
            Object[] strings = collection.toArray(stt);
            stt=null;
            return Arrays.asList(strings[i].toString());
        }

        log.info("没有得到合适的分片结果=:表名{},参数：{}",collection,columnNameAndShardingValuesMap);
        throw new RuntimeException("没有得到合适的分片结果");
    }

    @Override
    public void init() {

    }

    @Override
    public String getType() {
        return null;
    }

}
